import { getAddress, getDistance } from "@/api/index"
import { reactive, ref } from "vue"
import config from "@/utils/config"

export const useMap = () => {
    // 获取当前定位
    const location = reactive<{ latitude: number, longitude: number }>({
        latitude: 0,
        longitude: 0
    })
    const getLocation = () => {
        return new Promise((resolve, reject) => {
            uni.getLocation({
                type: 'gcj02',
                success: (res: any) => {
                    const { latitude, longitude } = res
                    location.latitude = latitude
                    location.longitude = longitude
                    resolve(location)
                },
                fail: (error) => {
                    console.log(error);
                    reject(error)
                }
            })
        })
    }
    // 解析的地址 https://lbs.qq.com/service/webService/webServiceGuide/address/Gcoder
    const { mapKey } = config
    const handlerGetAddress = async (location: number[]) => {
        const par = {
            key: mapKey, // 开发密钥（Key）
            location: location.join(","), // 经纬度（GCJ02坐标系），格式：location=lat<纬度>,lng<经度>
            get_poi: "0", // 是否返回周边poi列表，1为返回，0为不返回，不传默认为0
        }
        try {
            const res: any = await getAddress(par)
            return res.result
        } catch (error) {
            console.log(error);
            return {}
        }
    }
    // 计算距离 https://lbs.qq.com/service/webService/webServiceGuide/route/webServiceMatrix
    const handlerGetDistance = async (start: number[], end: number[]) => {
        const par = {
            key: mapKey, // 开发密钥（Key）
            from: start.join(","), // 起始点坐标，格式：lat,lng,[header],[roadtype],[speed],[accuracy],[timestamp]｜lat,lng,[header],[roadtype],[speed],[accuracy],[timestamp]…
            to: end.join(",") // 目标点坐标，格式: lat,lng;lat,lng… (经度与纬度用英文逗号分隔，坐标间用英文分号分隔）
        }
        try {
            const res: any = await getDistance(par)
            return res.result
        } catch (error) {
            console.log(error);
            return {}
        }
    }
    return {
        getLocation,
        handlerGetAddress,
        handlerGetDistance
    }
}